using AutoMapper;
using BaseData.CommonLib.Models;
using BaseData.DomainLib.AggregatesModel.CalculateUnitAggregate;
using MediatR;
using Swimj.CommonLib.Base;

namespace BaseData.ApplicationLib.Commands
{
    public class UpdateCalculateUnitCommand : CalculateUnitEditRequestDto, IRequest<Result<CalculateUnitInfoResponseDto>>
    {
        public int Id { get; set; }
    }

    public class UpdateCalculateUnitCommandHandler : IRequestHandler<UpdateCalculateUnitCommand, Result<CalculateUnitInfoResponseDto>>
    {

        private readonly ICalculateUnitRepository _calculateUnitRepository;
        private readonly IMapper _mapper;

        public UpdateCalculateUnitCommandHandler(ICalculateUnitRepository calculateUnitRepository,
        IMapper mapper)
        {
            _calculateUnitRepository = calculateUnitRepository;
            _mapper = mapper;
        }

        public async Task<Result<CalculateUnitInfoResponseDto>> Handle(UpdateCalculateUnitCommand request, CancellationToken cancellationToken)
        {
            var calculateUnit = await _calculateUnitRepository.Get(request.Id);
            calculateUnit?.Update(request.Name, request.Description);

            await _calculateUnitRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<CalculateUnitInfoResponseDto>.SuccessAsync(_mapper.Map<CalculateUnitInfoResponseDto>(calculateUnit));
        }
    }
}